/**
 * API接口模块
 * 提供与后端交互的方法，当前使用静态数据模拟
 */

const api = {
    /**
     * 获取文章列表
     * @param {Object} params - 查询参数
     * @param {number} params.page - 页码
     * @param {number} params.limit - 每页数量
     * @param {string} params.category - 分类筛选
     * @param {string} params.search - 搜索关键词
     * @returns {Promise} 返回文章列表数据
     */
    async getPosts(params = {}) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // 从本地文件加载数据
            const response = await fetch('../data/posts.json');
            const allPosts = await response.json();
            
            let filteredPosts = [...allPosts];
            
            // 分类筛选
            if (params.category) {
                filteredPosts = filteredPosts.filter(post => 
                    post.categories.includes(params.category)
                );
            }
            
            // 搜索筛选
            if (params.search) {
                const keyword = params.search.toLowerCase();
                filteredPosts = filteredPosts.filter(post => 
                    post.title.toLowerCase().includes(keyword) ||
                    post.content.toLowerCase().includes(keyword) ||
                    post.tags.some(tag => tag.toLowerCase().includes(keyword))
                );
            }
            
            // 排序：最新发布在前
            filteredPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
            
            // 分页
            const page = params.page || 1;
            const limit = params.limit || 10;
            const startIndex = (page - 1) * limit;
            const endIndex = startIndex + limit;
            const paginatedPosts = filteredPosts.slice(startIndex, endIndex);
            
            return {
                posts: paginatedPosts,
                total: filteredPosts.length,
                page,
                limit,
                totalPages: Math.ceil(filteredPosts.length / limit)
            };
        } catch (error) {
            console.error('Error fetching posts:', error);
            // 返回模拟数据
            return this.getMockPosts(params);
        }
    },

    /**
     * 获取文章详情
     * @param {string} id - 文章ID
     * @returns {Promise} 返回文章详情数据
     */
    async getPostById(id) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            const response = await fetch('../data/posts.json');
            const posts = await response.json();
            const post = posts.find(p => p.id === id);
            
            if (!post) {
                throw new Error('Post not found');
            }
            
            return post;
        } catch (error) {
            console.error('Error fetching post:', error);
            // 返回模拟数据
            return this.getMockPostById(id);
        }
    },

    /**
     * 获取文章分类
     * @returns {Promise} 返回分类列表
     */
    async getCategories() {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 200));
            
            const response = await fetch('../data/posts.json');
            const posts = await response.json();
            
            // 提取所有分类并计数
            const categoryMap = {};
            posts.forEach(post => {
                post.categories.forEach(category => {
                    categoryMap[category] = (categoryMap[category] || 0) + 1;
                });
            });
            
            // 转换为数组格式
            const categories = Object.entries(categoryMap).map(([name, count]) => ({
                name,
                count
            }));
            
            // 按数量排序
            categories.sort((a, b) => b.count - a.count);
            
            return categories;
        } catch (error) {
            console.error('Error fetching categories:', error);
            // 返回模拟数据
            return this.getMockCategories();
        }
    },

    /**
     * 获取热门文章
     * @param {number} limit - 返回数量
     * @returns {Promise} 返回热门文章列表
     */
    async getPopularPosts(limit = 5) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            const response = await fetch('../data/posts.json');
            const posts = await response.json();
            
            // 按浏览量排序，返回前N篇
            const popularPosts = [...posts]
                .sort((a, b) => b.views - a.views)
                .slice(0, limit);
            
            return popularPosts;
        } catch (error) {
            console.error('Error fetching popular posts:', error);
            // 返回模拟数据
            return this.getMockPopularPosts(limit);
        }
    },

    /**
     * 获取相关文章
     * @param {string} postId - 当前文章ID
     * @param {Array} categories - 当前文章分类
     * @param {number} limit - 返回数量
     * @returns {Promise} 返回相关文章列表
     */
    async getRelatedPosts(postId, categories, limit = 3) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            const response = await fetch('../data/posts.json');
            const posts = await response.json();
            
            // 筛选相同分类且不是当前文章的文章
            const relatedPosts = posts
                .filter(post => 
                    post.id !== postId && 
                    post.categories.some(cat => categories.includes(cat))
                )
                .sort((a, b) => b.views - a.views)
                .slice(0, limit);
            
            return relatedPosts;
        } catch (error) {
            console.error('Error fetching related posts:', error);
            // 返回模拟数据
            return this.getMockPopularPosts(limit);
        }
    },

    /**
     * 提交评论
     * @param {Object} commentData - 评论数据
     * @returns {Promise} 返回提交结果
     */
    async submitComment(commentData) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // 这里应该是实际的API调用
            // const response = await fetch('/api/comments', {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify(commentData)
            // });
            
            // 模拟成功响应
            return {
                success: true,
                message: '评论提交成功',
                comment: {
                    id: utils.generateUniqueId(),
                    ...commentData,
                    date: new Date().toISOString(),
                    approved: false
                }
            };
        } catch (error) {
            console.error('Error submitting comment:', error);
            return {
                success: false,
                message: '评论提交失败，请稍后重试'
            };
        }
    },

    /**
     * 提交联系表单
     * @param {Object} formData - 表单数据
     * @returns {Promise} 返回提交结果
     */
    async submitContactForm(formData) {
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 800));
            
            // 这里应该是实际的API调用
            // const response = await fetch('/api/contact', {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify(formData)
            // });
            
            // 模拟成功响应
            return {
                success: true,
                message: '消息发送成功，我们会尽快回复您'
            };
        } catch (error) {
            console.error('Error submitting contact form:', error);
            return {
                success: false,
                message: '消息发送失败，请稍后重试'
            };
        }
    },

    // 模拟数据方法
    getMockPosts(params = {}) {
        const mockPosts = [
            {
                id: '1',
                title: 'JavaScript 进阶技巧分享',
                excerpt: '本文分享一些实用的JavaScript进阶技巧，帮助你写出更优雅的代码。',
                content: '详细内容...',
                date: '2024-01-15',
                categories: ['JavaScript', '前端开发'],
                tags: ['ES6', '进阶', '技巧'],
                author: '博主',
                views: 1234,
                image: '../assets/images/js-tips.jpg'
            },
            {
                id: '2',
                title: 'CSS Grid 布局完全指南',
                excerpt: '深入了解CSS Grid布局，打造复杂而灵活的页面结构。',
                content: '详细内容...',
                date: '2024-01-10',
                categories: ['CSS', '前端开发'],
                tags: ['Grid', '布局', '响应式'],
                author: '博主',
                views: 987,
                image: '../assets/images/css-grid.jpg'
            },
            {
                id: '3',
                title: 'Vue.js 3 Composition API 实战',
                excerpt: '通过实际项目学习Vue.js 3的Composition API，提升开发效率。',
                content: '详细内容...',
                date: '2024-01-05',
                categories: ['Vue.js', '前端框架'],
                tags: ['Vue3', 'Composition API', '实战'],
                author: '博主',
                views: 2341,
                image: '../assets/images/vue3-composition.jpg'
            }
        ];
        
        return {
            posts: mockPosts,
            total: mockPosts.length,
            page: 1,
            limit: 10,
            totalPages: 1
        };
    },

    getMockPostById(id) {
        return {
            id,
            title: '模拟文章标题',
            excerpt: '模拟文章摘要...',
            content: '这是一篇模拟的文章内容。在实际应用中，这里会显示完整的文章内容。\n\n可以包含各种格式的文本，如标题、段落、列表等。',
            date: '2024-01-01',
            categories: ['模拟分类'],
            tags: ['模拟', '测试'],
            author: '博主',
            views: 123,
            image: '../assets/images/default-post.jpg'
        };
    },

    getMockCategories() {
        return [
            { name: 'JavaScript', count: 15 },
            { name: 'CSS', count: 12 },
            { name: 'Vue.js', count: 10 },
            { name: 'React', count: 8 },
            { name: '前端开发', count: 20 }
        ];
    },

    getMockPopularPosts(limit = 5) {
        const mockPosts = [
            {
                id: '101',
                title: '前端性能优化最佳实践',
                excerpt: '提升网站性能的关键技巧',
                date: '2024-01-14',
                views: 3210,
                image: '../assets/images/performance.jpg'
            },
            {
                id: '102',
                title: 'React Hooks 完全指南',
                excerpt: '从入门到精通React Hooks',
                date: '2024-01-12',
                views: 2890,
                image: '../assets/images/react-hooks.jpg'
            },
            {
                id: '103',
                title: 'TypeScript 实用技巧',
                excerpt: '让你的代码更加健壮',
                date: '2024-01-08',
                views: 1980,
                image: '../assets/images/typescript.jpg'
            }
        ];
        
        return mockPosts.slice(0, limit);
    }
};

// 导出API对象
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = api;
} else {
    window.api = api;
}